import React from 'react';
import { Modal, SearchBar, List } from 'antd-mobile';

import './index.less'

class Search extends React.Component<Props, State>{
    constructor(props) {
        super(props)

        this.state = {
            searchValue: ""
        }
    }
    changeTimer: number = 0;

    handleSearchChange = (val) => {
        this.setState({
            searchValue: val
        })
        if (this.changeTimer) {
            // 清除定时器
            window.clearInterval(this.changeTimer)
        }
        // 定时300ms后执行搜索
        this.changeTimer = window.setTimeout(() => {
            this.handleSearchSubmit(val)
        }, 300)

    }
    handleSearchSubmit = (val) => {
        // 如果还在定时，清除定时器
        if(this.changeTimer) {
            window.clearInterval(this.changeTimer)
        }

        this.props.onSearch && this.props.onSearch(val)
    }

    handleSelectItem = (sel) => {
        this.props.onSelect && this.props.onSelect(sel)
    }

    render() {
        let { searchValue } = this.state;
        let { visible, data, title, loading } = this.props;

        return (
            <Modal
                popup
                title={title}
                visible={visible}
                onClose={this.props.onClose}
                animationType="slide-up"
                className="slide-search"
            >
                <SearchBar 
                    value={searchValue}
                    placeholder="输入关键字搜索"
                    onChange={this.handleSearchChange}
                    onSubmit={this.handleSearchSubmit}
                    onCancel={this.props.onClose}
                />
                {
                    loading ? 
                        <div>加载中......</div>
                        :
                        (!data || !data.length) ?
                            <div>未搜索到内容</div>
                            :
                            <List className="slide-search-list">
                                {(data || []).map((item, index) => (
                                    <List.Item 
                                        key={index}
                                        onClick={() => this.handleSelectItem(item)}
                                    >{item.name}</List.Item>
                                ))}
                            </List>
                }
            </Modal>
        )
    }
}

export default Search